package com.mgg.gateway.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.mgg.common.dao.DaoSupport;
import com.mgg.gateway.service.AccessLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accessLogService")
public class AccessLogServiceImpl implements AccessLogService {

	@Autowired
	private DaoSupport dao;
	
	@Override
	public void saveAccessRecord(String url, Map<String, String> map, Map<String, String[]> paramMap) {
		try {
			Map<String,String> param = new HashMap<>();
			for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
				param.put(entry.getKey(), stringArrayEntryToString(entry.getValue()));
			}
			map.put("url", url);
			if (url.matches("^/mgg/goods/[0-9a-z]{32}$")) {
				param.put("goodsId", url.split("/mgg/goods/")[1]);
				map.put("url", "/mgg/goods/{goodsId}");
			} else if (url.matches("^/mgg/user/shop/info/[0-9a-zA-Z]{6,}$")) {
				param.put("shopCode", url.substring(20));
				map.put("url", "/mgg/user/shop/info/{shopCode}");
			} else if (url.matches("^/mgg/user/shop/[0-9a-zA-Z]{6,}/visit$")) {
				param.put("shopCode", url.substring(15).replace("/visit", ""));
				map.put("url", "/mgg/user/shop/{shopCode}/visit");
			} else if (url.matches("^/mgg/goods/[0-9a-z]{32}/rebate$")) {
				param.put("goodsId", url.substring(11,43));
				map.put("url", "/mgg/goods/{goodsId}/rebate");
			} else if (url.matches("^/mgg/user/query/byphone/[0-9]{11}$")) {
				param.put("phone", url.substring(24));
				map.put("url", "/mgg/user/query/byphone/{phone}");
			}
			
			map.put("goodsId", param.get("goodsId"));
			map.put("param", new Gson().toJson(param));
			dao.save("LogMapper.insertAppApiAccessRecord", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static String stringArrayEntryToString(String[] array) {
		String str = Arrays.toString(array);
		return str.substring(1, str.length() - 1);
	}
}
